import 'dart:async';

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../apis.dart';
import '../beans/loginbean.dart';
import '../const.dart';
import '../utils/mydio.dart';
import '../utils/utils.dart';
import '../view/textfield.dart';

class Register extends StatefulWidget {
  @override
  _RegisterState createState() => _RegisterState();
}

class _RegisterState extends State<Register> {
  Map<String, dynamic> data = Map();

  //定义变量
  Timer _timer;

  //倒计时数值
  var countdownTime = 0;
  var _scaffoldkey = new GlobalKey<ScaffoldState>();
  String mobile = '';

  //倒计时方法
  startCountdown() {
    countdownTime = 60;
    final call = (timer) {
      setState(() {
        if (countdownTime < 1) {
          _timer.cancel();
        } else {
          countdownTime -= 1;
        }
      });
    };
    _timer = Timer.periodic(Duration(seconds: 1), call);
  }

  void smsValidateCode() {
    mobile = data['loginName'];
    MyDio.getInstance().get(Apis.smsValidateCode + mobile, (data) async {
      print(data);
      if (data['resultCode'] == 0) {
        Utils.getInstance().showSnackBar(_scaffoldkey, '验证码发送成功');
        //成功
        startCountdown();
      } else {
        Utils.getInstance().showSnackBar(_scaffoldkey, data['msg']);
      }
    });
  }

  _handleCodeText() {
    return Text(
      countdownTime > 0 ? '${countdownTime}s后重新获取' : '获取验证码',
      style: TextStyle(
          fontSize: 17, color: countdownTime > 0 ? Const.grey : Const.gold),
    );
//    if (countdownTime > 0) {
//      return Text(${countdownTime}+'s后重新获取')
//    } else
//      return "获取验证码";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();

    if (_timer != null) {
      _timer.cancel();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      key: _scaffoldkey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Padding(
            padding: EdgeInsets.fromLTRB(33, 30, 33, 0),
            child: Column(
              children: <Widget>[
                EditText(
                  keyboardType: TextInputType.number,
                  data: data,
                  name: 'loginName',
                  labelText: '请输入手机号',
                  value: Utils.getInstance().checkEmpty(data['loginName'])
                      ? ''
                      : data['loginName'],
                ),
//                TextField(
//                  onChanged: (value) {
//                    data['loginName'] = value;
//                  },
//                  style: TextStyle(fontSize: 18, color: Colors.white),
//                  decoration: InputDecoration(
//                    labelText: '用户名',
//                    labelStyle: TextStyle(color: Const.grey, fontSize: 18),
//                    focusedBorder: UnderlineInputBorder(
//                        borderSide: BorderSide(
//                          color: Colors.white,
//                          width: 1,
//                        )),
//                    enabledBorder: UnderlineInputBorder(
//                        borderSide: BorderSide(
//                          color: Colors.white,
//                          width: 1,
//                        )),
//                  ),
//                ),
//                SizedBox(
//                  height: 20,
//                ),
                Stack(
                  alignment: Alignment.centerRight,
                  children: <Widget>[
                    EditText(
                      keyboardType: TextInputType.number,
                      data: data,
                      name: 'validCode',
                      labelText: '请输入验证码',
                      value: Utils.getInstance().checkEmpty(data['validCode'])
                          ? ''
                          : data['validCode'],
                    ),
//                    TextField(
//                      onChanged: (value) {
//                        data['validCode'] = value;
//                      },
//                      style: TextStyle(fontSize: 18, color: Colors.white),
//                      decoration: InputDecoration(
//                        labelText: '验证码',
//                        labelStyle: TextStyle(color: Const.grey, fontSize: 18),
//                        focusedBorder: UnderlineInputBorder(
//                            borderSide: BorderSide(
//                              color: Colors.white,
//                              width: 1,
//                            )),
//                        enabledBorder: UnderlineInputBorder(
//                            borderSide: BorderSide(
//                              color: Colors.white,
//                              width: 1,
//                            )),
//                      ),
//                    ),
                    GestureDetector(
                      onTap: () {
                        if (data['loginName'] == null) {
                          Utils.getInstance()
                              .showSnackBar(_scaffoldkey, '用户名不能为空');
                          return;
                        } else {
                          if (countdownTime == 0) {
                            smsValidateCode();
                          }
                        }
                      },
//                      child: Text('',style: TextStyle(fontSize: 17,color: Const.gold),),
                      child: _handleCodeText(),
                    ),
                  ],
                ),

                PassField(
                  labelText: '密码',
                  map: data,
                  mapKey: 'passwd',
                ),
              ],
            ),
          ),
          MaterialButton(
            height: 68,
            minWidth: MediaQuery.of(context).size.width,
            elevation: 0,
            onPressed: () {
              if (data['loginName'] == null) {
                Utils.getInstance().showSnackBar(_scaffoldkey, '用户名不能为空');
                return;
              }
              if (data['validCode'] == null) {
                Utils.getInstance().showSnackBar(_scaffoldkey, '验证码不能为空');
                return;
              }
              if (data['passwd'] == null) {
                Utils.getInstance().showSnackBar(_scaffoldkey, '密码不能为空');
                return;
              }
              MyDio.getInstance().post(Apis.register, (data) async {
                print(data);
                /**
                 * {resultCode: 0, record: {recordBh: 27071a57717541309d77a8cf91df1790, loginName: 15175972592, nickName: null, sex: null, phone: null, photo: null, password: null, enrollDate: 1570757456776, lastLoginDate: null, lastLoginModel: null}, msg: 注册成功！}
                 */
                if (data['resultCode'] == 0) {
                  SharedPreferences sp = await SharedPreferences.getInstance();
                  LoginBean loginBean = LoginBean.fromJson(data['record']);
                  Navigator.pop(context);
                } else {
                  Utils.getInstance().showSnackBar(_scaffoldkey, data['msg']);
                }
              }, params: data);
            },
            child: Text(
              "注    册",
              style: TextStyle(color: Colors.white, fontSize: 20),
            ),
            color: Const.gold,
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(30),
                    bottomRight: Radius.circular(30))),
          ),
        ],
      ),
    );
  }

//  String _md5Digest(String data) {
//    var content = new Utf8Encoder().convert(data);
//    var digest = md5.convert(content);
//    return hex.encode(digest.bytes);
//  }
}
